/*
 * Author: vyouzhi <vyouzhi@163.com>
 * http://www.xda.cn
 *
 * File: thread_lib.c
 * Create Date: 2011-08-05 16:54:05
 *
 */

#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <string.h>
#include <sys/epoll.h>

#include "thread_lib.h"
#include "socket_lib.h"
#include "proc_data_lib.h"
#include "mem_lib.h"

void Epoll_End(CThread_param *eparm){
	int  cfd, s;	
	struct epoll_event *event;
	
	cfd = *(eparm->client_fd);
	event = eparm->event;
	s = epoll_ctl(epoll_fd_r, EPOLL_CTL_DEL, cfd, event);
	if(-1 == s){
		printf("epoll_ctl error EPOLL_CTL_DEL\n");
	}
	SQLFree(eparm);
	close(cfd);
}


void *Runing(void *rarg){
	CThread_param *cparm;
	char *rBuff, *sBuff, *ssBuff;
	int slen=0, c_fd;

	/*printf("me is %ld -- thread\n", pthread_self());
	pthread_detach(pthread_self());*/
	
	cparm = (CThread_param *)rarg;

	c_fd = *(cparm->client_fd);
	slen = Socket_Recv(c_fd, &rBuff);
	if(slen == -1){
		Epoll_End(cparm);
		printf("--- error --\n");
		return (0);
	}	
	sBuff = strstr(rBuff, "<?xml");	

	if(sBuff == NULL){
		Epoll_End(cparm);
		return NULL;
	}

	slen = strlen(sBuff);
	ssBuff = SwitchData(sBuff);

	if(ssBuff == NULL){
		Epoll_End(cparm);
		return NULL;
	}
	slen = strlen(ssBuff);
	Socket_Send(c_fd, ssBuff, slen);

	Epoll_End(cparm);
	SQLFree(ssBuff);
	/*printf("-----end ----\n");*/
	return (0);
}

int Thread_Init(int epoll_fd, CThread_param *targ){
	pthread_t init_pt;

	epoll_fd_r = epoll_fd;
	pthread_create(&init_pt, NULL, Runing, (void *)targ);
	pthread_join(init_pt, NULL);
	return (0);
}

/* vim: set ts=4 sw=4: */

